# Copyright (C) 2009, 2010 Nathan Grubb

import sqlite3 as sqlite

try: # This module should run independently of the settings!
    from toasted.settings import DATABASE_PATH
except ImportError:
    DATABASE_PATH = None

class Database(object):
    """A class to represent an active sqlite connection. It provides methods
       to interact with that database.
    """    
    def __init__(self, database=None):
        self.database = database or DATABASE_PATH
        self.connection = sqlite.connect(self.database)
        self.cursor = self.connection.cursor()

    def __del__(self):
        self.close()

    def close(self):
        self.connection.close()

    def execute(self, query, variables=[], commit=True):
        """ Execute - runs a query on the database. Commits by default (commit=True).
            Returns the result of that query.
        """
        self.cursor.execute(query, variables)
        if commit is True:
            self.connection.commit()
        return [row for row in self.cursor]
    
    def query(self, query, *variables):
        """This function is provided for backwards compatibility and will be
           removed in Toasted 1.2. It has the same results as
           execute(query, variables, commit=False), use that instead.
        """
        return self.execute(query, variables=variables, commit=False)
    
    def connect(self):
        """This is provided for backwards compatibility and will be removed in Toasted
           1.2. __init__ automatically connects, so this just returns.
        """
        return